package cn.school.mybatis.controller;

import cn.school.mybatis.pojo.Admin;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

@Controller
@RequestMapping("/")
public class TestController {

    @RequestMapping("/sayHi")
    public String sayHi(HttpServletRequest request) {
        System.out.println("sayHi被调用");
        request.setAttribute("msg","666");
        return "welcome";
    }

    @RequestMapping("/sayHello")
    public ModelAndView sayHello( ) {
        System.out.println("sayHello被调用");
        ModelAndView mv=new ModelAndView();
        mv.addObject("msg","HelloSpring");
        mv.addObject("time","现在时间："+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date()));
        mv.setViewName("welcome");
        return mv;
    }

    @PostMapping("/login")
    public ModelAndView login(@RequestParam(value = "userName",required = true) String u, @RequestParam(value = "userPass",required = true) String p, HttpSession session){
        ModelAndView mv=new ModelAndView();
        if (u.startsWith("admin")&&p.length()>6){
            session.setAttribute("userName",u);
            mv.addObject("userName",u);
            mv.setViewName("welcome");
            return mv;
        }
        mv.setViewName("loginFail");
        return mv;
    }

    @PostMapping("/adminLogin")
    public ModelAndView adminLogin(@ModelAttribute("a") Admin admin, HttpSession session){
        ModelAndView mv=new ModelAndView();
        if (admin.getUsername().startsWith("admin")&&admin.getPassword().length()>3){
            session.setAttribute("userName",admin.getUsername());
            mv.addObject("userName",admin.getUsername());
            mv.setViewName("welcome");
            return mv;
        }
        mv.setViewName("loginFail");
        return mv;
    }


    @GetMapping("/regAdmin")
    public String regAdmin(Model model,@RequestParam Map map){
        System.out.println("=>>"+map);
        model.addAttribute("msg",map);
        return "welcome";

    }
    @RequestMapping("/toLogin")
    public String toLogin(HttpServletRequest request) {
        System.out.println("toLogin被调用");
        return "login";
    }
    @RequestMapping("/toReg")
    public String toReg(HttpServletRequest request) {
        System.out.println("toReg被调用");
        return "reg";
    }
}
